﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.SafetyConstruction.ViewModels;
using KingRoad.EPM.SafetyManagementEntity.Model;
using KingRoad.EPM.Web.Areas.SafetyConstruction.SafetyConstructionFramework.Common;
using System.IO;
using System.Data;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Text;
using NPOI.SS.Util;

namespace KingRoad.EPM.Web.Areas.SafetyConstruction.Controllers
{
    public class ScmSafeSupervisionController : BaseController
    {
        public const string RYGL_SGRY = "RYGL_AQJD";
        /// <summary>
        /// 重点建设项目安全监督台账-列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeSupervisionList(string pageName)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var safsupervisionList = ScmSafesupervisionUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Ss_Date", out totalRecord, "");

            int tempTotalRecord = 0;
            var allList = ScmSafesupervisionUIRule.GetAllCostplanmainForPage(1, ALL_RECORD_ITEMS, "Ss_Date", out tempTotalRecord, "");
            SetSectionValue(RYGL_SGRY, allList);

            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;


            return String.IsNullOrEmpty(pageName) ? View(new ScmSafeSupervisionViewModel { TheSafesupervisionList = safsupervisionList }) : View(pageName, new ScmSafeSupervisionViewModel { TheSafesupervisionList = safsupervisionList });
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(ScmSafeSupervisionViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);

            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return SafeSupervisionList("SafesupervisionList");

            ViewBag.iput_section = Request.Form["iput_section"];
            ViewBag.iput_question = Request.Form["iput_question"];
            ViewBag.iput_timestart = Request.Form["iput_timestart"];
            ViewBag.iput_timeend = Request.Form["iput_timeend"];
            string sql = " 1=1 ";
            if (ViewBag.iput_section != "")
                sql += " and Ss_Section like '%" + ViewBag.iput_section + "%' ";
            if (ViewBag.iput_question != "")
                sql += " and Ss_Problem like '%" + ViewBag.iput_question + "%' ";
            if (ViewBag.iput_timestart != "")
                sql += " and Ss_Date>='" + ViewBag.iput_timestart + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and Ss_Date<='" + ViewBag.iput_timeend + "' ";

            var safesupervisionList = ScmSafesupervisionUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Ss_Date", out totalRecord, sql);

            int tempTotalRecord = 0;
            var allList = ScmSafesupervisionUIRule.GetAllCostplanmainForPage(1, ALL_RECORD_ITEMS, "Ss_Date", out tempTotalRecord, sql);
            SetSectionValue(RYGL_SGRY, allList);


            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SafesupervisionList", new ScmSafeSupervisionViewModel { TheSafesupervisionList = safesupervisionList });
        }
        /// <summary>
        /// 重点建设项目安全监督台账-添加
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeSupervisionAdd()
        {
            return View();
        }
        /// <summary>
        /// 重点建设项目安全监督台账-添加 
        /// 功能：执行添加操作
        /// </summary>
        /// <returns></returns>
        public JsonResult SafesupervisionAddData(ScmSafeSupervisionViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.TheSafesupervisionInfo.Ss_ID = Guid.NewGuid().ToString();
                vm.TheSafesupervisionInfo.Ss_OperateUserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.TheSafesupervisionInfo.Ss_OperateUserName = GetLoginUserRealName;
                vm.TheSafesupervisionInfo.Ss_OperateTime = DateTime.Now;
                int safe = ScmSafesupervisionUIRule.AddSafesupervision(vm.TheSafesupervisionInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "SafetyConstruction.ScmSafeSupervision.SafeSupervisionList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 安全监督台账-删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SafesupervisionDelete(string id)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = ScmSafesupervisionUIRule.DeleteSafesupervision(id);
            });
            dynamic jsonReturn = new ExpandoObject();
            //删除成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "SafetyConstruction.ScmSafeSupervision.SafeSupervisionList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 安全监督台账-批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SafesupervisionMultiDelete()
        {
            dynamic jsonReturn = new ExpandoObject();
            var ids = base.GetRequestFormValue<string>("ids");
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = ScmSafesupervisionUIRule.DeleteSafesupervisionMulti(ids);
            });

            //保存成功
            if (true)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "SafetyConstruction.ScmSafeSupervision.SafeSupervisionList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 安全监督台账——编辑
        /// 功能：根据id加载相对应数据
        /// </summary>
        /// <returns></returns>
        public ActionResult SafesupervisionEdit(Guid id)
        {
            var SafesupervisionInfo = ScmSafesupervisionUIRule.GetSafesupervisionByID(id);
            return View(new ScmSafeSupervisionViewModel { TheSafesupervisionInfo = SafesupervisionInfo });
        }
        /// <summary>
        /// 安全监督台账-编辑（保存工作） 
        /// 功能：执行保存数据
        /// </summary>
        /// <returns></returns>
        public JsonResult SafesupervisionEditData(ScmSafeSupervisionViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.TheSafesupervisionInfo.Ss_OperateUserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.TheSafesupervisionInfo.Ss_OperateUserName = GetLoginUserRealName;
                vm.TheSafesupervisionInfo.Ss_OperateTime = DateTime.Now;
                int safe = ScmSafesupervisionUIRule.UpdateSafesupervision(vm.TheSafesupervisionInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "更新成功",
                    navTabId = "SafetyConstruction.ScmSafeSupervision.SafeSupervisionList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "更新失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 安全监督台账——查看
        /// </summary>
        /// <returns></returns>
        public ActionResult SafesupervisionDetail(Guid id)
        {
            var SafesupervisionInfo = ScmSafesupervisionUIRule.GetSafesupervisionByID(id);
            return View(new ScmSafeSupervisionViewModel { TheSafesupervisionInfo = SafesupervisionInfo });
        }
        /// <summary>
        /// Excel导出
        /// </summary>
        /// <returns></returns>
        public FileResult Excel()
        {
            //获取list数据           
            //   var list = ScmSafesupervisionUIRule.GetAllSafesupervision();
            var list = GetSessionValue<List<ScmSafesupervisionInfo>>(RYGL_SGRY);

            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //列宽度
            sheet1.SetColumnWidth(0, 5 * 256);
            sheet1.SetColumnWidth(1, 15 * 256);
            sheet1.SetColumnWidth(2, 15 * 256);
            sheet1.SetColumnWidth(3, 25 * 256);
            sheet1.SetColumnWidth(4, 15 * 256);
            sheet1.SetColumnWidth(5, 15 * 256);
            sheet1.SetColumnWidth(6, 25 * 256);
            sheet1.SetColumnWidth(7, 15 * 256);
            sheet1.SetColumnWidth(8, 15 * 256);
            //设置第一行
            IRow row0 = sheet1.CreateRow(0);
            //行高
            row0.Height = 30 * 20;
            //合并单元格
            sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 8));
            //创建单元格
            CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), "重点建设项目安全监督台账");
            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(1);
            //行高
            row1.Height = 25 * 20;
            CreateCell(row1, 0, Getcellstyle(book, "center", true, 10, 600), "序号");
            CreateCell(row1, 1, Getcellstyle(book, "center", true, 10, 600), "存在问题标段");
            CreateCell(row1, 2, Getcellstyle(book, "center", true, 10, 600), "通报文号");
            CreateCell(row1, 3, Getcellstyle(book, "center", true, 10, 600), "存在的主要问题");
            CreateCell(row1, 4, Getcellstyle(book, "center", true, 10, 600), "标段整改责任人");
            CreateCell(row1, 5, Getcellstyle(book, "center", true, 10, 600), "督办人");
            CreateCell(row1, 6, Getcellstyle(book, "center", true, 10, 600), "整改及回复情况");
            CreateCell(row1, 7, Getcellstyle(book, "center", true, 10, 600), "日期");
            CreateCell(row1, 8, Getcellstyle(book, "center", true, 10, 600), "备注");
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 2);
                CreateCell(rowtemp, 0, Getcellstyle(book), (i + 1).ToString());
                CreateCell(rowtemp, 1, Getcellstyle(book), list[i].Ss_Section);
                CreateCell(rowtemp, 2, Getcellstyle(book), list[i].Ss_DocumentNumb);
                CreateCell(rowtemp, 3, Getcellstyle(book), list[i].Ss_Problem);
                CreateCell(rowtemp, 4, Getcellstyle(book), list[i].Ss_CorrectCharge);
                CreateCell(rowtemp, 5, Getcellstyle(book), list[i].Ss_Supervise);
                CreateCell(rowtemp, 6, Getcellstyle(book), list[i].Ss_CorrectReply);
                CreateCell(rowtemp, 7, Getcellstyle(book), list[i].Ss_Date == null ? "" : Convert.ToDateTime(list[i].Ss_Date).ToString("yyyy-MM-dd"));
                CreateCell(rowtemp, 8, Getcellstyle(book), list[i].Ss_Remark);
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            string fileName = HttpUtility.UrlEncode("重点建设项目安全监督台账.xls", Encoding.GetEncoding("UTF-8"));
            return File(ms, "application/vnd.ms-excel", fileName);

        }
        #region Excel导入
        /// <summary>
        /// Excel导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public JsonResult ImportExcelFile(HttpPostedFileBase FileData)
        {
            string infor = "";
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (FileData != null)
                {
                    string tempFileName = FileData.FileName;
                    string fileExt = Path.GetExtension(tempFileName).ToLower();
                    string fileName = Guid.NewGuid().ToString() + fileExt;
                    string tempPath = "/TempleterFilePath";
                    if (!tempPath.EndsWith("/"))
                        tempPath += "/";
                    tempPath = Server.MapPath(tempPath);
                    if (!Directory.Exists(tempPath))
                        Directory.CreateDirectory(tempPath);
                    tempPath = Path.Combine(tempPath, fileName);
                    FileData.SaveAs(tempPath);
                    if (string.IsNullOrWhiteSpace(tempPath) || !System.IO.File.Exists(tempPath))
                    {
                        throw new Exception("导入文件不存在");
                    }

                    HSSFWorkbook hssfworkbook;

                    //读取文件流
                    using (FileStream fs = System.IO.File.OpenRead(tempPath))
                    {
                        hssfworkbook = new HSSFWorkbook(fs);
                        //获取第一个工作簿
                        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
                        {
                            var ret = ExcelImportValidation.Validation<ScmSafesupervisionInfo>(sheet);
                            if (ret.Item1)
                            {
                                //获取第一行
                                IRow headerRow = sheet.GetRow(0);
                                //列数
                                int cellCount = headerRow.LastCellNum;
                                //行数
                                int rowCount = sheet.LastRowNum;
                                //循环行
                                for (int i = 1; i <= rowCount; i++)
                                {
                                    IRow row = sheet.GetRow(i);
                                    //重点建设项目安全监督台账
                                    ScmSafesupervisionInfo info = new ScmSafesupervisionInfo();
                                    info.Ss_ID = Guid.NewGuid().ToString();
                                    info.Ss_OperateTime = DateTime.Now;
                                    //操作人ID及名称 添加权限时赋值
                                    info.Ss_OperateUserID = GetLoginUserId;
                                    info.Ss_OperateUserName = GetLoginUserRealName;
                                    //读取该行信息
                                    info.Ss_Section = GetCellValue(row.GetCell(0));
                                    info.Ss_DocumentNumb = GetCellValue(row.GetCell(1));
                                    info.Ss_Problem = GetCellValue(row.GetCell(2));
                                    info.Ss_CorrectCharge = GetCellValue(row.GetCell(3));
                                    info.Ss_Supervise = GetCellValue(row.GetCell(4));
                                    info.Ss_CorrectReply = GetCellValue(row.GetCell(5));
                                    if (GetCellValue(row.GetCell(6)) != "")
                                        info.Ss_Date = Convert.ToDateTime(GetCellValue(row.GetCell(6)));
                                    info.Ss_Remark = GetCellValue(row.GetCell(7));
                                    //向数据库插入数据 
                                    ScmSafesupervisionUIRule.AddSafesupervision(info);
                                }
                            }
                            else
                            {
                                infor = ret.Item2;
                            }

                        }
                    }
                    //删除临时文件
                    System.IO.File.Delete(tempPath);
                }


            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                if (infor == "")
                {
                    jsonReturn = new
                    {
                        statusCode = "200",
                        message = "导入成功",
                        navTabId = "",
                        rel = "",
                        callbackType = "",
                        forwardUrl = "",
                        confirmMsg = ""
                    };
                }
                else
                {
                    jsonReturn = new
                    {
                        statusCode = "300",
                        message = "导入失败!  " + infor,
                    };
                }

            }

            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "导入失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        //public JsonResult ImportExcelFile(int[] datas)
        //{
        //    string infor = "";
        //    var isScuess = TryCatchCommand.TryExec(() =>
        //    {
        //        HSSFWorkbook hssfworkbook;

        //        var bytes = datas.ToList().ConvertAll(x => (byte)x).ToArray();
        //        //读取文件流
        //        using (Stream file = new MemoryStream(bytes))
        //        {
        //            hssfworkbook = new HSSFWorkbook(file);
        //        }
        //        //获取第一个工作簿
        //        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
        //        {
        //            var ret = ExcelImportValidation.Validation<ScmSafesupervisionInfo>(sheet);
        //            if (ret.Item1)
        //            {
        //                //获取第一行
        //                IRow headerRow = sheet.GetRow(0);
        //                //列数
        //                int cellCount = headerRow.LastCellNum;
        //                //行数
        //                int rowCount = sheet.LastRowNum;
        //                //循环行
        //                for (int i = 1; i <= rowCount; i++)
        //                {
        //                    IRow row = sheet.GetRow(i);
        //                    //重点建设项目安全监督台账
        //                    ScmSafesupervisionInfo info = new ScmSafesupervisionInfo();
        //                    info.Ss_ID = Guid.NewGuid().ToString();
        //                    info.Ss_OperateTime = DateTime.Now;
        //                    //操作人ID及名称 添加权限时赋值
        //                    info.Ss_OperateUserID = GetLoginUserId;
        //                    info.Ss_OperateUserName = GetLoginUserRealName;
        //                    //读取该行信息
        //                    info.Ss_Section = GetCellValue(row.GetCell(0));
        //                    info.Ss_DocumentNumb = GetCellValue(row.GetCell(1));
        //                    info.Ss_Problem = GetCellValue(row.GetCell(2));
        //                    info.Ss_CorrectCharge = GetCellValue(row.GetCell(3));
        //                    info.Ss_Supervise = GetCellValue(row.GetCell(4));
        //                    info.Ss_CorrectReply = GetCellValue(row.GetCell(5));
        //                    if (GetCellValue(row.GetCell(6)) != "")
        //                        info.Ss_Date = Convert.ToDateTime(GetCellValue(row.GetCell(6)));
        //                    info.Ss_Remark = GetCellValue(row.GetCell(7));
        //                    //向数据库插入数据 
        //                    ScmSafesupervisionUIRule.AddSafesupervision(info);
        //                }
        //            }
        //            else
        //            {
        //                infor = ret.Item2;
        //            }

        //        }
        //    });
        //    dynamic jsonReturn = new ExpandoObject();
        //    //保存成功
        //    if (isScuess)
        //    {
        //        if (infor=="")
        //        {
        //            jsonReturn = new
        //            {
        //                statusCode = "200",
        //                message = "导入成功",
        //                navTabId = "",
        //                rel = "",
        //                callbackType = "",
        //                forwardUrl = "",
        //                confirmMsg = ""
        //            }; 
        //        }
        //        else
        //        {
        //            jsonReturn = new
        //            {
        //                statusCode = "300",
        //                message = "导入失败!  " + infor,
        //            };  
        //        }

        //    }

        //    else
        //    {
        //        jsonReturn = new
        //        {
        //            statusCode = "300",
        //            message = "导入失败",
        //        };
        //    }
        //    return new JsonResult()
        //    {
        //        Data = jsonReturn
        //    };
        //}

        #endregion


    }
}
